package com.sunshine.lnuplusweb.utils

import com.google.gson.Gson
import com.google.gson.JsonParser
import com.google.gson.reflect.TypeToken
import com.sunshine.lnuplusweb.callback.LoginCallback
import com.sunshine.lnuplusweb.entities.Lesson
import com.sunshine.lnuplusweb.vo.superlesson.SuperData
import com.sunshine.lnuplusweb.vo.superlesson.SuperLessonBean
import okhttp3.*
import java.io.IOException
import java.lang.Exception

class LoadSuperLesson {
    fun load(
            which: Int,
            scheduleId: Int,
            superData: SuperData,
            loginCallback: LoginCallback<MutableList<Lesson>>
    ){
        val okHttpClient = OkHttpClient()
                .newBuilder()
                .followRedirects(false)
                .build()
        val requestBody = FormBody.Builder()

                .add("phoneModel", "MI 8")
                .add("phoneBrand", "Xiaomi")
                .add("channel", "xiaomi")
                .add("beginYear", superData.superList[which].beginYear)
                .add("term", superData.superList[which].term)
                .add("platform", "1")
                .add("versionNumber", "9.5.9")
                .add("phoneVersion", "29")
                .build()
        val request = Request.Builder()
                .url("http://120.55.151.61/V2/Course/getCourseTableFromServer.action")
                .header("Cookie", superData.cookie!!)
                .post(requestBody)
                .build()
        okHttpClient.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                loginCallback.onFail("没有网络连接")
            }

            override fun onResponse(call: Call, response: Response) {
                val body = response.body?.string()
                if(body.isNullOrEmpty()){
                    loginCallback.onFail("课表解析失败")
                }else{
                    try {
                        val jsonArray = JsonParser
                                .parseString(body)
                                .asJsonObject
                                .getAsJsonObject("data")
                                .getAsJsonArray("lessonList")

                        val superLessonList = ArrayList<SuperLessonBean>()
                        jsonArray.forEach {
                            val superLessonBean: SuperLessonBean =
                                    Gson().fromJson(it, object : TypeToken<SuperLessonBean>(){}.type)
                            superLessonList.add(superLessonBean)
                        }
                        parseSuperLesson(loginCallback, scheduleId, superLessonList)
                    }catch (e: Exception){
                        loginCallback.onFail("$e 发生异常")
                    }
                }
            }
        })
    }

    private fun parseSuperLesson(loginCallback: LoginCallback<MutableList<Lesson>>, scheduleId: Int, superLessonList: ArrayList<SuperLessonBean>) {
        try {
            val lessonList = ArrayList<Lesson>()
            superLessonList.forEach {
                val weeks = it.smartPeriod.replace(" ", ",")
                val lesson = Lesson(
                        scheduleId,
                        it.id.toString(),
                        it.day,
                        it.sectionstart,
                        0,
                        it.sectionend,
                        0,
                        it.name,
                        //判断教师是否为空，否则replace会报错
                        if (it.teacher == null) "" else it.teacher.replace("*", ""),
                        if (it.locale != null) it.locale else "",
                        weeks,
                        "0"
                )
                lessonList.add(lesson)
            }

            loginCallback.onSuccess(lessonList)
        }catch (e: Exception){
            var string = "错误信息：$e\n"
            string += superLessonList
            loginCallback.onFail(string)
        }
    }
}